//
//  VGIMImageViewController.swift
//  IMTest
//
//  Created by 宋海胜 on 2019/4/24.
//  Copyright © 2019年 宋海胜. All rights reserved.
//  相片大图展示、视频播放页

import UIKit

class VGIMImageViewController: UIViewController, UIScrollViewDelegate {

    fileprivate var imgUrl: String!
    fileprivate var thumbUrl: String!
    
    fileprivate var imageView: UIImageView = {
        let view: UIImageView = UIImageView()
        view.contentMode = UIView.ContentMode.scaleAspectFit
        view.isUserInteractionEnabled = true
        return view
    }()
    
    fileprivate var placeholderImage: UIImageView = {
        let view: UIImageView = UIImageView()
        view.contentMode = UIView.ContentMode.scaleAspectFit
        return view
    }()
    
    fileprivate lazy var backBt: UIButton = {
        let bt: UIButton = UIButton(frame: CGRect(x: 0, y: NAV_HEIGHT - 44, width: 58, height: 46))
        bt.setImage(UIImage(named: "back_white"), for: .normal)
        bt.imageView?.sizeToFit()
        bt.addTarget(self, action: #selector(backBtAction), for: .touchUpInside)
        return bt
    }()
    
    fileprivate lazy var longGes: UILongPressGestureRecognizer = {
        let ges: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction))
        ges.minimumPressDuration = 0.3
        return ges
    }()
    
    fileprivate lazy var doubleTapGes: UITapGestureRecognizer = {
        let ges: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTapAction))
        ges.numberOfTapsRequired = 2
        ges.numberOfTouchesRequired = 1
        return ges
    }()
    
    fileprivate lazy var backScrollView: UIScrollView = {
        let view: UIScrollView = UIScrollView()
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.maximumZoomScale = 2;
        if #available(iOS 11.0, *) {
            view.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        }
        return view
    }()
    
    @objc init(_ dic: NSDictionary) {
        super.init(nibName: nil, bundle: nil)
        self.imgUrl = (dic["imageURL"] as! String)
        self.thumbUrl = (dic["thumbPath"] as! String)
        print("imgUrl:\(self.imgUrl ?? "")  thumbUrl:\(self.thumbUrl ?? "")")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .black
        setupImage()
        self.title = "相片大图展示、视频播放页"
    }
    

    fileprivate func setupImage() {
        
        self.view.addSubview(self.backScrollView)
        self.backScrollView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        backScrollView.addSubview(self.imageView)
        self.imageView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        self.view.addSubview(self.backBt)
        self.imageView.addGestureRecognizer(self.longGes)
        self.imageView.addGestureRecognizer(self.doubleTapGes)
        doubleTapGes.require(toFail: longGes)
        
        
        NIMSDK.shared().resourceManager.fetchNOSURL(withURL: self.imgUrl) { (error, urlStr) in
            let url: URL = URL(string: urlStr ?? "")!
            self.placeholderImage.image = UIImage(contentsOfFile: self.thumbUrl)
            self.imageView.sd_setImage(with: url, placeholderImage: self.placeholderImage.image, options: SDWebImageOptions(rawValue: SDWebImageOptions.retryFailed.rawValue | SDWebImageOptions.avoidAutoSetImage.rawValue), completed: { (image, error, cacheType, imageUrl) in
                if (error == nil) {
                    self.imageView.image = image
                }
            })
        }
    }

    @objc func backBtAction() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func longPressAction() {
        
        if let image = self.imageView.image {
            
//            UIAlertController.vg_alertVC(title: "保存图片", message: "", actionSureTitle: "", actionCancelTitle: "", selfVC: self), compeletionClosure: { (alertAction) in
//
//            }
            
            let alertController = UIAlertController(title: "保存图片", message: "", preferredStyle: .alert)
            let saveAction = UIAlertAction(title: "保存", style: .default) { (action: UIAlertAction) in
//                image.vg_saveImageToAlumb()
            }
            alertController.addAction(saveAction)
            
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.vg_present(alertController, animated: true, completion: nil)
        }
    }
    
    @objc func doubleTapAction(sender: UITapGestureRecognizer) {
        if (self.backScrollView.zoomScale <= 1.0) {
            let touchPoint: CGPoint = sender.location(in: self.backScrollView)
            let scaleX = touchPoint.x + self.backScrollView.contentOffset.x
            let scaleY = touchPoint.y + self.backScrollView.contentOffset.y
            // 放大到最大比例2
            self.backScrollView.zoom(to: CGRect(x: scaleX, y: scaleY, width: 10, height: 10), animated: true)
        } else {
            self.backScrollView.setZoomScale(1, animated: true)
        }
    }
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.imageView
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        // 计算imageview的center
        let scrContentSize: CGSize = scrollView.contentSize
        let scrBoundsSize: CGSize = scrollView.bounds.size
        let offsetX: CGFloat = (scrBoundsSize.width > scrContentSize.width) ? (scrBoundsSize.width - scrContentSize.width) * 0.5 : 0.0 // x偏移
        let offsetY: CGFloat = (scrContentSize.height > scrContentSize.height) ? (scrBoundsSize.height - scrContentSize.height) * 0.5 : 0.0 // y偏移
        let actualCenter: CGPoint = CGPoint(x: scrContentSize.width * 0.5 + offsetX, y: scrContentSize.height * 0.5 + offsetY)
        self.imageView.center = actualCenter
    }
    
//    - (void)loadPullUpMessagesWithComplete:(void (^)(NSInteger, NSArray *, NSError *))handler {
//    __block NIMMessageModel *currentNewestMsg = self.items.lastObject;
//    __block NSInteger index = 0;
//    NIMMessageSearchOption *option = [NIMMessageSearchOption new];
//    option.startTime = currentNewestMsg.messageTime - 0.1;
//    option.limit = [NIMKit sharedKit].config.messageLimit;
//    option.allMessageTypes = YES;
//    option.order = NIMMessageSearchOrderAsc;
//    __weak typeof(self) wself = self;
//    [[NIMSDK sharedSDK].conversationManager searchMessages:_currentSession
//    option:option
//    result:^(NSError * _Nullable error, NSArray<NIMMessage *> * _Nullable messages) {
//    index = [wself appendMessageModels:[self modelsWithMessages:messages]].count;
//    if (handler) {
//    NIMKit_Dispatch_Async_Main(^{
//    handler(index,messages,nil);
//    });
//    }
//    }];
//    }
}
